<template>
  <div>
    <div>
      <el-form :inline="true" :model="selectProduct" ref="selectProduct" class="demo-form-inline" >
        <el-row :gutter="5">
          <el-col :span="6">
            <el-form-item prop="productCommodityCode" label="商品条形码:" style="width:100%" label-width="90px">
              <el-input v-model="selectProduct.productCommodityCode" placeholder="商品条形码"
                        size="medium" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="productTitle" label="商品名称:" style="width:100%" label-width="90px">
              <el-input v-model="selectProduct.productTitle" placeholder="商品名称"  size="medium"
                        autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="retailPrice" label="商品零售价:" style="width:100%" label-width="90px">
              <el-input v-model="selectProduct.retailPrice" placeholder="商品零售价"  size="medium"
                        autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="createDate" label="创建时间:" style="width:100%" label-width="90px">
              <el-date-picker
                  v-model="selectProduct.createDate"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                    :default-time="['00:00:00', '23:59:59']" style="width:215px" size="medium"  autocomplete="off" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item prop="selectTypeValue" label="商品类型:" style="width:100%" label-width="90px">
            <el-select v-model="selectTypeValue" filterable placeholder="请选择" size="medium"  autocomplete="off"  clearable>
              <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" >
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" style="text-align: right">
            <el-form-item>
              <el-button type="primary" @click="onSubmit('selectProduct')" size="medium">查询</el-button>
              <el-button @click="resetForm('selectProduct')" size="medium">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-card style="width: 100%;  height: calc(100vh - 325px);" >
        <el-row>
          <el-col :span="22">
            <el-popover
                placement="right"
                width="350"
                trigger="click" v-model="showPopover"   @hide="handleHide">
              <el-form :model="showCol" status-icon  ref="columnValues" class="demo-ruleForm">
                <el-form-item>
                  <el-checkbox-group v-model="columnValues" @change="handleCheckedCitiesChange">
                    <el-row :gutter="20">
                      <el-col :span="8" v-for="col in columns">
                        <el-checkbox  :label="col" :key="col">{{col}}</el-checkbox>
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item style="text-align: right">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" style="margin-right: 20px">全选</el-checkbox>
                  <el-button type="primary" @click="submitFormShowCol('showCol')" size="mini">应用</el-button>
                  <el-button @click="resetFormShowCol('showCol')" size="mini">重置</el-button>
                </el-form-item>
              </el-form>
              <el-button  slot="reference" type="primary" plain size = "small" icon="el-icon-s-tools">自定义列</el-button>
            </el-popover>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" icon="el-icon-plus" size="small " @click="insertProduct">添加商品</el-button>
          </el-col>
        </el-row>
      <template>
            <el-table :data="tableData" max-height="270"  v-loading="loading"   element-loading-text="拼命加载中"
                      element-loading-spinner="el-icon-loading" >
              <template slot="empty"><el-empty :image-size="100" description='暂无数据'></el-empty></template>
          <el-table-column fixed prop="id" label="编号" sortable></el-table-column>
          <el-table-column fixed prop="productCommodityCode" v-if="showCol.includes('商品条形码')" label="商品条形码" width="200" sortable></el-table-column>
          <el-table-column prop="productTitle" v-if="showCol.includes('商品名称')" label="商品名称" width="200" ></el-table-column>
          <el-table-column prop="purchasePrice" v-if="showCol.includes('商品进货价')"label="商品进货价" width="120"></el-table-column>
          <el-table-column prop="retailPrice" v-if="showCol.includes('商品零售价')" label="商品零售价" width="120" sortable></el-table-column>
          <el-table-column prop="productInventory" v-if="showCol.includes('库存')" label="库存" width="120" sortable></el-table-column>
          <el-table-column prop="typeName" v-if="showCol.includes('商品类型名称')" label="商品类型名称" width="120"></el-table-column>
          <el-table-column prop="createBy" v-if="showCol.includes('创建人')" label="创建人" width="150"></el-table-column>
          <el-table-column prop="createDate" v-if="showCol.includes('创建时间')" label="创建时间" width="180" sortable></el-table-column>
          <el-table-column prop="lastUpdateBy"  v-if="showCol.includes('修改人')"label="修改人" width="150"></el-table-column>
          <el-table-column prop="lastUpdateDate" v-if="showCol.includes('修改时间')" label="修改时间" width="180" sortable></el-table-column>
          <el-table-column fixed="right" label="操作" width="120" >
            <template slot-scope="scope">
              <el-button
                  @click="update(scope.$index, tableData)"
                  type="text"
                  size="small">
                编辑
              </el-button>
              <el-button
                  @click="delete(scope.$index, tableData)"
                  type="text"
                  size="small" style="color:red;">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
        <div class="block" style="margin-top: 15px;text-align: right">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10,20, 50, 100, 200,500]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total" background small>
          </el-pagination>
        </div>
      </el-card>
    </div>
    <el-drawer
        title="添加商品信息"
        :before-close="handleClose"
        :visible.sync="dialog"
        direction="rtl"
        custom-class="demo-drawer"
        ref="drawer"
        size="50%"
    >
      <div class="demo-drawer__content">
        <el-form :model="insertData" :rules="rules" ref="insertData" label-width="200px" style="margin-top: 50px;">
            <el-form-item label="商品条形码："  prop="productCommodityCode">
            <el-autocomplete
                v-model="insertData.productCommodityCode"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入商品条形码"
                @select="insertHandleSelect"  style="width: 70%;"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="商品名称："  prop="productTitle" >
            <el-input v-model="insertData.productTitle" autocomplete="off"  style="width: 70%;" :disabled="insertDataDisabled.productTitleDisabled" clearable></el-input>
          </el-form-item>
          <el-form-item label="商品进货价：" prop="purchasePrice" >
            <el-input-number v-model="insertData.purchasePrice"   :precision="2" :step="0.1"  autocomplete="off" style="width: 70%;" :disabled="insertDataDisabled.purchasePriceDisabled" clearable></el-input-number>
          </el-form-item>
          <el-form-item label="商品零售价：" prop="retailPrice">
            <el-input-number v-model="insertData.retailPrice"    :precision="2" :step="0.1"   autocomplete="off" style="width: 70%;" :disabled="insertDataDisabled.retailPriceDisabled" clearable></el-input-number>
          </el-form-item>
          <el-form-item label="商品类型：" prop="typeId">
            <el-select v-model="insertData.typeId"   autocomplete="off" style="width: 70%;" :disabled="insertDataDisabled.typeIdDisabled" placeholder="请选择" size="medium"  clearable>
              <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" >
              </el-option>
            </el-select>

          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer" style="text-align: center;margin-top: 25px">
          <el-button type="primary"  @click="insertSubmitForm('insertData')"  :loading="digloading">{{ digloading ? '提交中 ...' : '确 定' }}</el-button>
          <el-button @click="cancelForm">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectProduct: {
        productCommodityCode: null,
        productTitle: null,
        retailPrice: null,
        createDate:[]
      },tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      loading: false,
      selectTypeValue:"",
      typeList:[],
      showCol:['商品条形码','商品名称','商品进货价','商品零售价','库存','商品类型名称','创建人','创建时间','修改人','修改时间'],
      columnValues:['商品条形码','商品名称','商品进货价','商品零售价','库存','商品类型名称','创建人','创建时间','修改人','修改时间'],
      columns:['商品条形码','商品名称','商品进货价','商品零售价','库存','商品类型名称','创建人','创建时间','修改人','修改时间'],
      checkAll: true,
      isIndeterminate: true,
      showPopover: false,
      dialog:false,
      digloading:false,
      insertData:{productCommodityCode:"",productTitle:"",purchasePrice:0.0,retailPrice:0.0,typeId:""},
      restaurants: [],
      timeout:  null,
      insertDataDisabled: {productTitleDisabled:false,purchasePriceDisabled:false,retailPriceDisabled:false,typeIdDisabled:false},
      rules: {
        productCommodityCode: [
        { required: true, message: '请输入商品条形码', trigger: 'change' },
      ],
        productTitle: [
        { required: true, message: '请输入商品名称', trigger: 'change' }
      ],
        purchasePrice: [
        { required: true, message: '请输入商品进货价', trigger: 'change' },
      ],
        retailPrice: [
        { required: true, message: '请输入商品零售价', trigger: 'change' }
      ],
        typeId: [
        {  required: true, message: '请选择商品类型', trigger: 'change' }
      ]
    }
    }
  },
  methods: {
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      let bool = false;
      var results = queryString ? restaurants.filter((item) => {
        if (item.value == queryString)
        {
          this.insertHandleSelect(item);
          bool = true;
          return bool;
        }
        else if (item.value.indexOf(queryString) != -1){
          return true;
        }
      }) : restaurants;
        if (bool == false)
        {
          this.insertData.productTitle = '';
          this.insertData.purchasePrice = 0.0;
          this.insertData.purchasePrice = 0.0;
          this.insertData.typeId = '';
          this.insertDataDisabled = {productTitleDisabled:false,purchasePriceDisabled:false,retailPriceDisabled:false,typeIdDisabled:false};
        }
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    insertHandleSelect(item) {
      this.insertData.productTitle = item.productTitle;
      this.insertData.purchasePrice = item.purchasePrice;
      this.insertData.retailPrice = item.retailPrice;
      this.insertData.typeId = item.typeId;
      this.insertDataDisabled.typeIdDisabled = true;
      this.insertDataDisabled.productTitleDisabled = true;
      this.insertDataDisabled.retailPriceDisabled = true;
      this.insertDataDisabled.purchasePriceDisabled = true;
    },
    insertProduct(){
      this.dialog = true;
    },
    handleClose(done) {
      if (this.digloading) {
        return;
      }
      this.cancelForm();
    },
    insertSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
        this.insert();
        } else {
          return false;
        }
      });
    },
    cancelForm() {
      this.digloading = false;
      this.dialog = false;
      this.insertData = {productCommodityCode:"",productTitle:"",purchasePrice:0.0,retailPrice:0.0,typeId:""};
      this.insertDataDisabled = {productTitleDisabled:false,purchasePriceDisabled:false,retailPriceDisabled:false,typeIdDisabled:false};
      clearTimeout(this.timer);
    },
    handleCheckAllChange(val) {
      this.columnValues = val ? this.columns : [];
      this.isIndeterminate = false;
    }, handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.columns.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columns.length;
    },
    submitFormShowCol(formName) {
      this.showCol = this.columnValues;
      this.showPopover = false;
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    resetFormShowCol(formName) {
      this.columnValues = ['商品条形码','商品名称','商品进货价','商品零售价','库存','商品类型名称','创建人','创建时间','修改人','修改时间']
      this.showCol = this.columnValues;
      this.showPopover = false;
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    handleHide()
    {
      this.columnValues = this.showCol;
    },
    onSubmit(formName) {
      console.log(this.selectProduct);
      let data ={
        productCommodityCode: this.selectProduct.productCommodityCode,
        productTitle: this.selectProduct.productTitle,
        retailPrice: this.selectProduct.retailPrice,
        createDateStart: this.selectProduct.createDate == null || this.selectProduct.createDate.length == 0? null : this.formatDate(this.selectProduct.createDate[0]),
        createDateEnd: this.selectProduct.createDate == null || this.selectProduct.createDate.length == 0? null : this.formatDate(this.selectProduct.createDate[1]),
        typeId: this.selectTypeValue,
        page:this.currentPage,
        pageSize:this.pageSize
      }
      console.log(data)
      //let data = Object.assign({},  this.selectProduct, {page:this.currentPage,pageSize:this.pageSize});
     this.selectQueryList(data);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.selectTypeValue  = '';
      this.selectProduct.createDate = [];
    },
    update(row,data)
    {

    },
    delete(row,data)
    {

    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    insert()
    {
      let url = "http://114.55.111.65:9090/product/insert";
      //let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6IntcInVzZXJJZFwiOjF9IiwiZXhwIjoxNjk0MTU2NzY5fQ.2l7X0-E8twF3EJt9Ek1bVFv0T7rq0UJCw8oLCZFKZV0";
      this.loading = true;
      this.axios.post(url,this.insertData,{headers: {
          'token': localStorage.getItem("token")
        }}).then(reponse =>{
        let code = reponse.data.statusCode;
        if (code == "200")
        {
          this.$message.success("添加成功！");
          let selectProduct = {page:this.currentPage,pageSize:this.pageSize};
          this.selectQueryList(selectProduct);
          this.cancelForm();
        }
        else {
          this.$notify.error({
            title: '错误',
            message: reponse.data.message
          });
        }
      }).catch(error => {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        });
      });
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    }
    ,
    selectQueryList(selectProduct)
    {
      let url = "http://114.55.111.65:9090/product/query-list";
      //let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6IntcInVzZXJJZFwiOjF9IiwiZXhwIjoxNjk0MTU2NzY5fQ.2l7X0-E8twF3EJt9Ek1bVFv0T7rq0UJCw8oLCZFKZV0";
      this.loading = true;
      this.axios.post(url,selectProduct,{headers: {
          'token': localStorage.getItem("token")
    }}).then(reponse =>{
      let code = reponse.data.statusCode;
      if (code == "200")
      {
        this.tableData = reponse.data.data.records;
        this.total = reponse.data.data.total;
        if (this.restaurants.length==0)
        {
          this.tableData.forEach(item=>{
            this.restaurants.push({
              "value":item.productCommodityCode,
              "productTitle":item.productTitle,
              "purchasePrice":item.purchasePrice,
              "retailPrice":item.retailPrice,
              "typeId":item.typeId
            })
          })
        }
      }
      else {
        this.$notify.error({
          title: '错误',
          message: reponse.data.message
        });
      }
    }).catch(error => {
      console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        });
      });
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    selectTypeList()
    {
      let url = "http://114.55.111.65:9090/type/query-list";
      //let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6IntcInVzZXJJZFwiOjF9IiwiZXhwIjoxNjk0MTU2NzY5fQ.2l7X0-E8twF3EJt9Ek1bVFv0T7rq0UJCw8oLCZFKZV0";
      this.axios.post(url,null,{headers: {
          'token': localStorage.getItem("token")
        }}).then(reponse =>{
        let code = reponse.data.statusCode;
        if (code == "200")
        {
          reponse.data.data.forEach(item =>{
            this.typeList.push({
              value: item.id,
              label: item.typeName
            })
          });
        }
      }).catch(error => {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        });
      });
    },
    formatDate(dateString) {
      let date = new Date(dateString);

      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2);
      let day = ("0" + date.getDate()).slice(-2);

      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);

      let formattedDateTime = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

      return formattedDateTime;
    }
  },
  mounted() {
    if (localStorage.getItem("token") == null)
    {
      this.$notify.error({
        title: '错误',
        message: '未登录,请先登录!'
      });
      this.$router.push("/login");
    }
    let selectProduct = {page:this.currentPage,pageSize:this.pageSize};
    this.selectQueryList(selectProduct);
    this.selectTypeList();
  }
}
</script>

<style>

</style>